import { ref, nextTick } from 'vue';
import * as THREE from 'three';
import BIRDS from 'vanta/dist/vanta.birds.min';
import { router } from '/@/router';

// 响应式数据
export const currentScreen = ref(1);
export const screen1 = ref<HTMLElement | null>(null);
export const screen2 = ref<HTMLElement | null>(null);
let vantaEffect: any = null;

// 头像点击计数器
export const avatarClickCount = ref(0);
export const lastClickTime = ref(0);
const CLICK_TIMEOUT = 3000; // 3秒内需要完成6次点击
const REQUIRED_CLICKS = 6; // 需要点击6次

// 向下滚动提示显示状态
export const showScrollHint = ref(false);

// 页面切换状态
export const isTransitioning = ref(false);

// echo按键序列
export const echoSequence = ref('');
const ECHO_TIMEOUT = 3000; // 3秒内需要完成echo输入
const ECHO_TARGET = 'echo';

// back按键序列
export const backSequence = ref('');
const BACK_TIMEOUT = 3000; // 3秒内需要完成back输入
const BACK_TARGET = 'back';

// 头像点击处理
export const handleAvatarClick = (event: Event) => {
  console.log('🎯 头像被点击了！', event);

  const currentTime = Date.now();

  // 如果距离上次点击超过3秒，重置计数器
  if (currentTime - lastClickTime.value > CLICK_TIMEOUT) {
    avatarClickCount.value = 0;
    console.log('⏰ 重置点击计数器');
  }

  avatarClickCount.value++;
  lastClickTime.value = currentTime;

  // 添加点击动画效果
  const avatar = document.querySelector('.avatar') as HTMLElement;
  if (avatar) {
    avatar.classList.add('avatar-clicked');
    setTimeout(() => {
      avatar.classList.remove('avatar-clicked');
    }, 200);
  }

  // 显示点击进度
  console.log(`📊 点击进度: ${avatarClickCount.value}/${REQUIRED_CLICKS}`);

  // 如果达到6次点击，跳转到登录页
  if (avatarClickCount.value >= REQUIRED_CLICKS) {
    // 重置计数器
    avatarClickCount.value = 0;

    // 显示成功提示
    console.log('🎉 成功触发登录页跳转！');

    // 跳转到登录页
    // 这里假设登录页的路由是 '/login'，你可以根据实际路由调整
    window.location.href = '/login';
    // 或者使用 Vue Router（如果已配置）
    // router.push('/login');
  }
};

// 导航点击处理
export const handleNavClick = (type: string) => {
  if (isTransitioning.value) return; // 防止重复点击

  console.log(`🎯 点击了导航: ${type}`);

  // 添加点击反馈
  const event = window.event as any;
  const card = event?.target?.closest('.neon-card') as HTMLElement;
  if (card) {
    card.style.transform = 'scale(0.95)';
    setTimeout(() => {
      card.style.transform = '';
    }, 150);
  }

  // 根据类型执行不同的操作
  switch (type) {
    case 'about':
      // 跳转到关于页面
      console.log('📖 跳转到关于页面');
      router.push('/blog/about');
      break;
    case 'github':
      // 跳转到GitHub
      console.log('🐙 跳转到GitHub');
      window.open('https://github.com/Accompany-Z', '_blank');
      break;
    case 'articles':
      // 跳转到文章
      console.log('📚 跳转到文章');
      router.push('/blog/articles');
      break;
    case 'projects':
      // 跳转到项目展示
      console.log('💼 跳转到项目展示');
      router.push('/blog/projects');
      break;
    case 'contact':
      // 跳转到联系页面
      console.log('📧 跳转到联系页面');
      router.push('/blog/contact');
      break;
    case 'scripts':
      // 跳转到快捷脚本
      console.log('🚀 跳转到快捷脚本');
      router.push('/blog/scripts');
      break;
    case 'message':
      // 跳转到留言板
      console.log('📝 跳转到留言板');
      router.push('/blog/message');
      break;
    default:
      console.log('❓ 未知的导航类型');
  }
};

// 初始化vanta.js背景
const initVantaBackground = () => {
  try {
    if (typeof window !== 'undefined') {
      vantaEffect = BIRDS({
        el: document.body,
        THREE: THREE,
        mouseControls: true,
        touchControls: true,
        gyroControls: false,
        minHeight: 200,
        minWidth: 200,
        scale: 1,
        scaleMobile: 1,
        backgroundColor: 0x0a0a0a,
        color1: 0x1890ff,
        color2: 0x52c41a,
        colorMode: 'lerpGradient',
        birdSize: 1.5,
        wingSpan: 20,
        separation: 50,
        alignment: 1,
        cohesion: 1,
        quantity: 4,
      });
    }
  } catch (error) {
    console.warn('⚠️ Vanta.js 背景初始化失败:', error);
  }
};

// 控制页面滚动
const controlScroll = (enabled: boolean) => {
  try {
    if (enabled) {
      // 启用滚动但保持滚动条隐藏
      document.body.style.overflow = 'auto';
      document.documentElement.style.overflow = 'auto';
    } else {
      // 禁用滚动
      document.body.style.overflow = 'hidden';
      document.documentElement.style.overflow = 'hidden';
    }
  } catch (error) {
    console.warn('⚠️ 滚动控制失败:', error);
  }
};

// 滚动到下一屏
export const scrollToNext = async () => {
  if (isTransitioning.value) return; // 防止重复点击

  try {
    isTransitioning.value = true;

    // 添加按钮点击动画
    const button = document.querySelector('.down-button') as HTMLElement;
    if (button) {
      button.style.transform = 'scale(0.9)';
      setTimeout(() => {
        button.style.transform = '';
      }, 150);
    }

    // 添加页面切换动画
    const screen1Element = screen1.value;
    if (screen1Element) {
      // 第一屏淡出动画
      screen1Element.style.transition = 'all 0.8s ease';
      screen1Element.style.opacity = '0';
      screen1Element.style.transform = 'translateY(-50px)';
    }

    // 延迟切换到第二屏
    setTimeout(() => {
      currentScreen.value = 2;

      // 第二屏淡入动画
      nextTick(() => {
        const screen2Element = screen2.value;
        if (screen2Element) {
          screen2Element.style.transition = 'all 0.8s ease';
          screen2Element.style.opacity = '0';
          screen2Element.style.transform = 'translateY(50px)';

          // 触发淡入动画
          setTimeout(() => {
            screen2Element.style.opacity = '1';
            screen2Element.style.transform = 'translateY(0)';
            isTransitioning.value = false;
          }, 50);
        }
      });
    }, 400);
  } catch (error) {
    console.error('❌ 页面切换失败:', error);
    isTransitioning.value = false;
  }
};

// 返回第一屏
export const backToFirst = async () => {
  if (isTransitioning.value) return; // 防止重复点击

  try {
    isTransitioning.value = true;

    // 添加页面切换动画
    const screen2Element = screen2.value;
    if (screen2Element) {
      // 第二屏淡出动画
      screen2Element.style.transition = 'all 0.8s ease';
      screen2Element.style.opacity = '0';
      screen2Element.style.transform = 'translateY(50px)';
    }

    // 延迟切换到第一屏
    setTimeout(() => {
      currentScreen.value = 1;

      // 第一屏淡入动画
      nextTick(() => {
        const screen1Element = screen1.value;
        if (screen1Element) {
          screen1Element.style.transition = 'all 0.8s ease';
          screen1Element.style.opacity = '0';
          screen1Element.style.transform = 'translateY(-50px)';

          // 触发淡入动画
          setTimeout(() => {
            screen1Element.style.opacity = '1';
            screen1Element.style.transform = 'translateY(0)';
            isTransitioning.value = false;
          }, 50);
        }
      });
    }, 400);
  } catch (error) {
    console.error('❌ 返回第一屏失败:', error);
    isTransitioning.value = false;
  }
};

// 组件挂载
export const onMountedHandler = () => {
  // 启用滚动但保持滚动条隐藏
  controlScroll(true);

  // 确保滚动条隐藏但保持滚动功能
  document.documentElement.style.overflow = 'auto';
  document.body.style.overflow = 'auto';

  // 添加CSS类来确保滚动条隐藏但保持滚动功能
  document.documentElement.classList.add('no-scrollbar');
  document.body.classList.add('no-scrollbar');

  // 初始化背景
  initVantaBackground();

  // 添加键盘事件监听 - echo和back序列
  const handleKeydown = (event: KeyboardEvent) => {
    const currentTime = Date.now();

    // 忽略左箭头键，让其他页面处理
    if (event.key === 'ArrowLeft') {
      return;
    }

    // 处理echo序列（第一屏）
    if (currentScreen.value === 1) {
      // 如果超过3秒没有按键，重置序列
      if (currentTime - lastClickTime.value > ECHO_TIMEOUT) {
        echoSequence.value = '';
      }

      // 添加按键到序列
      echoSequence.value += event.key.toLowerCase();
      lastClickTime.value = currentTime;

      console.log('🔤 Echo序列:', echoSequence.value); // 添加调试日志

      // 检查是否匹配echo
      if (echoSequence.value.includes(ECHO_TARGET)) {
        console.log('🎉 检测到echo序列，跳转到登录页！');
        echoSequence.value = '';
        window.location.href = '/login';
      }

      // 保持序列长度合理
      if (echoSequence.value.length > 10) {
        echoSequence.value = echoSequence.value.slice(-5);
      }
    }

    // 处理back序列（第二屏）
    if (currentScreen.value === 2) {
      // 如果超过3秒没有按键，重置序列
      if (currentTime - lastClickTime.value > BACK_TIMEOUT) {
        backSequence.value = '';
      }

      // 添加按键到序列
      backSequence.value += event.key.toLowerCase();
      lastClickTime.value = currentTime;

      console.log('🔤 Back序列:', backSequence.value); // 添加调试日志

      // 检查是否匹配back
      if (backSequence.value.includes(BACK_TARGET)) {
        console.log('🎉 检测到back序列，返回第一屏！');
        backSequence.value = '';
        backToFirst();
      }

      // 保持序列长度合理
      if (backSequence.value.length > 10) {
        backSequence.value = backSequence.value.slice(-5);
      }
    }
  };

  document.addEventListener('keydown', handleKeydown);

  // 测试头像点击事件
  console.log('🔧 组件已挂载，头像点击功能已启用');
  console.log('💡 提示：快速连续点击头像6次可以进入登录页');
  console.log('⌨️ 键盘彩蛋：第一屏依次按下echo字母可以进入登录页');
  console.log('⌨️ 键盘彩蛋：第二屏依次按下back字母可以返回第一屏');

  // 添加一个测试点击事件
  setTimeout(() => {
    const avatarWrapper = document.querySelector('.avatar-wrapper');
    if (avatarWrapper) {
      console.log('✅ 头像容器已找到，点击事件已绑定');
    } else {
      console.log('❌ 头像容器未找到');
    }
  }, 1000);

  // 返回清理函数
  return () => {
    document.removeEventListener('keydown', handleKeydown);
    console.log('🧹 键盘事件监听器已清理');
  };
};

// 组件卸载
export const onUnmountedHandler = () => {
  // 清理vanta效果
  if (vantaEffect) {
    vantaEffect.destroy();
  }

  // 移除CSS类
  document.documentElement.classList.remove('no-scrollbar');
  document.body.classList.remove('no-scrollbar');

  // 恢复滚动
  controlScroll(true);
};
